package common

import (
	"alertmanagerWebhook/config"
	"alertmanagerWebhook/global"
	"alertmanagerWebhook/utils"
	"fmt"
	"strings"
)

type MarkdownTransformer struct {
	generator *MessageGenerator
}

func NewMarkdownTransformer() (*MarkdownTransformer, error) {
	global.Logger.Debug("创建Markdown转换器实例")
	generator, err := NewMessageGenerator()
	if err != nil {
		global.Logger.Errorf("创建消息生成器失败: %v", err)
		return nil, err
	}
	return &MarkdownTransformer{generator: generator}, nil
}

func (t *MarkdownTransformer) Transform(notification config.Notification, platform string) (interface{}, error) {
	global.Logger.Debugf("开始转换%s告警通知%v，共%d条告警", platform, notification, len(notification.Alerts))

	firingContent, resolvedContent, err := t.generator.GenerateAlertContent(notification, platform)
	if err != nil {
		global.Logger.Errorf("生成告警内容失败: %v", err)
		return nil, fmt.Errorf("failed to generate alert content: %w", err)
	}

	global.Logger.Debugf("获取到告警内容 - 触发中: %d字符, 已恢复: %d字符",
		len(firingContent), len(resolvedContent))

	// 合并触发和恢复的告警内容
	// combinedContent := firingContent
	// if resolvedContent != "" {
	// 	if combinedContent != "" {
	// 		combinedContent += "\n\n"
	// 	}
	// 	// 保留原有的@信息
	// 	combinedContent += resolvedContent
	// }

	// if combinedContent == "" {
	// 	global.Logger.Info("没有有效的告警内容需要处理")
	// 	return nil, nil
	// }

	// global.Logger.Debugf("生成最终%s Markdown内容，长度: %d字符", platform, len(combinedContent))

	switch platform {
	case "dingding":
		atMobiles := global.Config.DingDing.AtMobiles
		// 确保@信息在每条告警消息中
		if len(atMobiles) > 0 {
			if firingContent != "" {
				firingContent += "\n\n@" + strings.Join(atMobiles, " @")
			}
			if resolvedContent != "" {
				resolvedContent += "\n\n@" + strings.Join(atMobiles, " @")
			}
		}
		combinedContent := firingContent
		if resolvedContent != "" {
			if combinedContent != "" {
				combinedContent += "\n\n"
			}
			combinedContent += resolvedContent
		}
		return config.NewDingDingMarkdown("告警通知", combinedContent, atMobiles), nil

	default: // wechat
		atMobiles := global.Config.QyWeChat.AtMobiles
		combinedContent := firingContent
		if resolvedContent != "" {
			if combinedContent != "" {
				combinedContent += "\n\n"
			}
			combinedContent += resolvedContent
		}

		if len(atMobiles) > 0 {
			// 统一在消息末尾添加@信息
			userIDs, err := utils.ConvertMobilesToUserIDs(atMobiles)
			if err != nil {
				global.Logger.Errorf("转换手机号到userid失败: %v", err)
				// 如果转换失败，仍然使用手机号
				combinedContent += "\n\n@" + strings.Join(atMobiles, " @")
			} else {
				// 使用转换后的userid，格式为<@userid>
				for _, userID := range userIDs {
					combinedContent += fmt.Sprintf(" <@%s>", userID)
				}
			}
		}
		return config.NewQyWeChatMarkdown(combinedContent, atMobiles), nil
	}
}
